package com.cskaoyan.gateway.controller.user;

import com.cskaoyan.gateway.Dto.LoginOfPostDto;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IMemberService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;

@RestController
@RequestMapping("/user/")
public class MemberController {


    @Reference(timeout = 3000,check = false)
    IKaptchaService iKaptchaService;
    @Reference(timeout = 10000,check = false)
    IMemberService iMemberService;

    @RequestMapping("verify")
    @Anoymous
    public ResponseData userVerify(String uid,String username){

       ResponseData responseData  =   iMemberService.userVerify(username);

         return  responseData;

    }



    /**
     * 用户注册
     * @param map
     * @param request
     * @return
     */
    @PostMapping("register")
    @Anoymous
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest request){

        //拿到验证码
        String captcha = map.get("captcha");
        Object resp =  verifyCaptcha(request, captcha);
        if (resp != null){
            return (ResponseData)resp;
        }



        //验证码校验成功
        //检查用户是否存在
        String email = map.get("email");
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");

        //将数据塞入dto
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);

        // 传到具体的service层并返回响应
        ResponseData responseData = iMemberService.addMember(userRegisterRequest);
        return responseData;



    }

    private ResponseData verifyCaptcha(HttpServletRequest request, String captcha) {
        //获取cookie里的kaptcha-uuid
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");

        //校验验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.requestCheck();
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        //TODO 这里到底是getImageCode 还是 getCode？
        String code = kaptchaCodeResponse.getCode();
        if (!code.equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<String>().setErrorMsg("请求数据校验失败");
        }
        else return null;
    }

    /**
     * 用户登录
     */
    @PostMapping("login")
    @Anoymous
    public ResponseData loginOfPost(@RequestBody Map<String,String> map, HttpServletRequest request,HttpServletResponse response ){
        //验证码校验
        String captcha = map.get("captcha");
        Object resp =  verifyCaptcha(request, captcha);
        if (resp != null){
            return (ResponseData)resp;
        }
        //验证用户
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        UserLoginResponse userLoginResponse = iMemberService.queryMemberByUserNameAndPassword(userLoginRequest);



        if (userLoginResponse == null){
            //验证失败
            return new ResponseUtil<String>().setErrorMsg("用户名或密码不正确");
        }
        if (!iMemberService.isVerify(userName)){
            return new ResponseUtil<String>().setErrorMsg("用户未验证，请查看邮件以进行验证！");
        }
        else {
            //验证成功
            LoginOfPostDto loginOfPostDto = new LoginOfPostDto();
            loginOfPostDto.setCode("000000").setMsg("成功").setId(userLoginResponse.getId())
                    .setUsername(userLoginResponse.getUsername()).setPhone(userLoginResponse.getPhone())
                    .setEmail(userLoginResponse.getEmail()).setSex(userLoginResponse.getSex())
                    .setAddress(userLoginResponse.getAddress()).setFile(userLoginResponse.getFile())
                    .setDescription(userLoginResponse.getDescription()).setPoints(userLoginResponse.getPoints())
                    .setBalance(userLoginResponse.getBalance()).setState(userLoginResponse.getState());

            Cookie cookie = CookieUtil.genCookie("access_token", userLoginResponse.getToken(), "/", 3600);
            CookieUtil.setCookie(response,cookie);
            return new ResponseUtil<LoginOfPostDto>().setData(loginOfPostDto);
        }

    }

    @GetMapping("login")
    @Anoymous
    public ResponseData loginByGet(HttpServletRequest request){
        //拿到token
        String token = CookieUtil.getCookieValue(request, "access_token");
        if (token == null){
            return new ResponseUtil<String>().setErrorMsg("");
        }
        ResponseData responseData = iMemberService.queryMemberByToken(token);
        return responseData;
    }

    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response){
        Cookie cookie = CookieUtil.genCookie("access_token", null, "/", 0);
        CookieUtil.setCookie(response,cookie);

        return new ResponseUtil<String>().setData("success");

    }
}
